<template>
  <div class="AllStaffInformation">
    <!-- 搜索框 -->
    <a-form
      ref="formRef"
      name="advanced_search"
      class="ant-advanced-search-form"
      :model="formState"
    >
      <!-- 输入框 -->
      <div class="chaxun">
        <div class="ssBox">
          <a-row :gutter="24" style="margin-left: 30px">
            <a-col :span="8">
              <a-form-item label="姓名">
                <a-input
                  v-model:value="formState.name"
                  placeholder="请输入姓名"
                  style="width: 300px"
                ></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="教职工号">
                <a-input
                  v-model:value="formState.num"
                  placeholder="请输入教职工号"
                  style="width: 300px"
                  class="sInput"
                ></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="组织">
                <!-- 级联选择器 -->
                <a-cascader
                  v-model:value="formState.organization"
                  :options="options"
                  placeholder="请选择组织"
                  style="width: 300px"
                />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="24" style="margin-left: 30px">
            <a-col :span="8">
              <a-form-item label="性别">
                <a-select
                  v-model:value="formState.sex"
                  placeholder="请选择性别"
                  style="width: 300px"
                >
                  <a-select-option value="男">男</a-select-option>
                  <a-select-option value="女">女</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>

            <a-col :span="8" style="margin-left: 15px">
              <a-form-item label="手机号">
                <a-input
                  v-model:value="formState.phone"
                  placeholder="请输入手机号"
                  style="width: 300px"
                  class="sInput"
                ></a-input>
              </a-form-item>
            </a-col>
          </a-row>
        </div>

        <div class="aButton">
          <a-button type="primary" @click="search">查询</a-button>
          <!-- <a-button type="primary" style="margin-left: 30px" @click="addTeacher">增加 </a-button> -->

          <a-button type="primary" @click="showModal" style="margin-left: 30px">添加老师</a-button>
          <a-modal
            v-model:visible="visible"
            title="Basic Modal"
            @ok="handleOk"
            :after-close="afterClose"
          >
            <a-form
              :model="formStateModal"
              name="basic"
              :label-col="{ span: 8 }"
              :wrapper-col="{ span: 16 }"
            >
              <a-form-item label="姓名">
                <a-input
                  v-model:value="formStateModal.name"
                  placeholder="请输入姓名"
                  style="width: 300px"
                ></a-input>
              </a-form-item>

              <a-form-item label="教职工号">
                <a-input
                  v-model:value="formStateModal.num"
                  placeholder="请输入教职工号"
                  style="width: 300px"
                  class="sInput"
                ></a-input>
              </a-form-item>
              <a-form-item label="请输入手机号">
                <a-input
                  v-model:value="formStateModal.phone"
                  placeholder="请输入手机号"
                  style="width: 300px"
                ></a-input>
              </a-form-item>

              <a-form-item label="组织">
                <!-- 级联选择器 -->
                <a-cascader
                  v-model:value="formStateModal.organization"
                  :options="options"
                  placeholder="请选择组织"
                  style="width: 300px"
                />
              </a-form-item>

              <a-form-item label="性别">
                <a-select
                  v-model:value="formStateModal.sex"
                  placeholder="请选择性别"
                  style="width: 300px"
                >
                  <a-select-option value="男">男</a-select-option>
                  <a-select-option value="女">女</a-select-option>
                </a-select>
              </a-form-item>
            </a-form>
          </a-modal>

          <a-button style="margin-left: 30px" @click="resetFormData">清空</a-button>
        </div>
      </div>
    </a-form>
    <div class="search-result-list">
      <a-table :columns="columns" :data-source="dataSource" bordered :pagination="false">
        <!-- 编辑功能按钮 -->
        <template #bodyCell="{ column, text, record }">
          <template
            v-if="['teacherName', 'num', 'department', 'phone', 'sex'].includes(column.dataIndex)"
          >
            <div>
              <a-input
                v-if="editableData[record.key]"
                v-model:value="editableData[record.key][column.dataIndex]"
                style="margin: -5px 0"
              />
              <template v-else>
                {{ text }}
              </template>
            </div>
          </template>
          <template v-else-if="column.dataIndex === 'operation'">
            <div class="editable-row-operations">
              <span v-if="editableData[record.key]">
                <a-typography-link @click="save(record.key, record)" style="margin-right: 10px"
                  >保存</a-typography-link
                >
                <a-popconfirm title="确定要取消?" @confirm="cancel(record.key)">
                  <a>取消</a>
                </a-popconfirm>
              </span>
              <span v-else>
                <a @click="edit(record.key)">编辑</a>
              </span>
            </div>
          </template>
          <!-- 删除功能按钮 -->
          <template v-if="column.dataIndex === 'name'">
            <div class="editable-cell">
              <div v-if="editableData[record.key]" class="editable-cell-input-wrapper">
                <a-input
                  v-model:value="editableData[record.key].name"
                  @pressEnter="save(record.key)"
                />
                <check-outlined class="editable-cell-icon-check" @click="save(record.key)" />
              </div>
              <div v-else class="editable-cell-text-wrapper">
                {{ text || ' ' }}
                <edit-outlined class="editable-cell-icon" @click="edit(record.key)" />
              </div>
            </div>
          </template>
          <template v-else-if="column.dataIndex === 'operation'">
            <a-popconfirm
              v-if="dataSource.length"
              title="确定要删除吗?"
              @confirm="onDelete(record.key)"
            >
              <a>删除</a>
            </a-popconfirm>
          </template>
        </template>
      </a-table>
      <div style="border: 1px solid #fff">
        <a-pagination
          v-model:current="currentIndex"
          v-model:page-size="pageSizeIndex"
          :total="totalSize"
          :show-total="(total) => `共 ${total} 条数据`"
          style="margin-top: 15px; margin-left: 15px; margin-bottom: 15px"
          :onChange="onChange"
        />
      </div>
    </div>
    <a-alert
      message="添加学生成功！"
      type="success"
      :banner="true"
      style="margin-top: -800px; width: 300px; margin-left: 550px"
      v-if="showSuccess"
      class="animate__animated animate__fadeIn"
    />

    <a-alert
      message="请输入完整的信息！"
      type="error"
      :banner="true"
      style="margin-top: -800px; width: 300px; margin-left: 550px"
      v-if="showError"
      class="animate__animated animate__fadeIn"
    />
  </div>
</template>

<script>
import { defineComponent, reactive, ref, onMounted } from 'vue'
import {
  teacherInfo,
  teacherChange,
  teacherDelete,
  teacherSearch,
  teacherAdd
} from '@/api/teacher.js'
import { DownOutlined, UpOutlined, EditOutlined, CheckOutlined } from '@ant-design/icons-vue'
import { cloneDeep } from 'lodash-es'
import useRoleInfo from '@/store/roleInfo.js'

// 表格格式
const columns = [
  {
    title: '姓名',
    dataIndex: 'teacherName',
    width: '10%'
  },
  {
    title: '教职工号',
    dataIndex: 'tnumber',
    width: '20%'
  },
  {
    title: '组织',
    dataIndex: 'department',
    width: '30%'
  },
  {
    title: '手机号',
    dataIndex: 'phone',
    width: '20%'
  },
  {
    title: '性别',
    dataIndex: 'sex',
    width: '10%'
  },
  {
    title: '操作',
    dataIndex: 'operation'
  }
]

// 级联选择器数据
let options = [
  {
    id: '1-1',
    value: '电子信息工程学院',
    label: '电子信息工程学院',
    children: [
      {
        value: '20计科1班',
        label: '20计科1班'
      },

      {
        value: '19计科2班',
        label: '19计科2班'
      },

      {
        value: '18计科1班',
        label: '18计科1班'
      },
      {
        value: '20网工1班',
        label: '20网工1班'
      },

      {
        value: '19网工2班',
        label: '19网工2班'
      },

      {
        value: '21网工3班',
        label: '21网工3班'
      }
    ]
  },
  {
    id: '1-2',
    value: '粤台学院',
    label: '粤台学院',
    children: [
      {
        value: '20智能科学与技术1班',
        label: '20智能科学与技术1班'
      },
      {
        value: '20智能科学与技术2班',
        label: '20智能科学与技术2班'
      },
      {
        value: '19智能科学与技术1班',
        label: '19智能科学与技术1班'
      }
    ]
  }
]

export default defineComponent({
  components: {
    DownOutlined,
    UpOutlined,
    EditOutlined,
    CheckOutlined
  },
  setup() {
    const roleInfo = useRoleInfo()
    let currentIndex = ref(1)
    let pageSizeIndex = ref(5)
    let totalSize = ref(0)
    const params = { page: currentIndex.value, pageSize: pageSizeIndex.value }
    // 获取表格数据方法
    const getInfo = async () => {
      const firstData = { page: 1, pageSize: 5 }
      const info = await teacherInfo(firstData)
      totalSize.value = info.total
      for (let i = 0; i < info.records.length; i++) {
        const fInfo = {
          key: info.records[i].id,
          teacherName: info.records[i].teacherName,
          department: info.records[i].department + '/' + info.records[i].tclass,
          sex: info.records[i].sex,
          phone: info.records[i].phone,
          tnumber: info.records[i].tnumber
        }
        const data = dataSource.value
        if (!data.find((item) => item.key === info.records[i].id)) {
          dataSource.value.push(fInfo)
        }
      }
    }
    const formRef = ref()
    const sex = ref()
    const formState = reactive({
      num: '',
      name: '',
      organization: '',
      phone: '',
      sex: ''
    })
    const formStateModal = reactive({
      num: '',
      name: '',
      organization: '',
      phone: '',
      sex: ''
    })

    const resetFormData = () => {
      formState.name = ''
      formState.num = ''
      formState.organization = ''
      formState.phone = ''
      formState.sex = ''
    }

    const dataSource = ref([])
    const editableData = reactive({})
    // 编辑
    const edit = (key) => {
      editableData[key] = cloneDeep(dataSource.value.filter((item) => key === item.key)[0])
    }
    // 保存
    const save = (key, record) => {
      Object.assign(dataSource.value.filter((item) => key === item.key)[0], editableData[key])

      const data = {
        id: record.key,
        teacherName: record.teacherName,
        department: record.department.split('/')[0],
        tclass: record.department.split('/')[1],
        sex: record.sex,
        phone: record.phone,
        tnumber: record.num
      }

      teacherChange(data).then((res) => {
        console.log(res)
      })
      delete editableData[key]
    }
    // 取消
    const cancel = (key) => {
      delete editableData[key]
    }
    // 删除
    const onDelete = async (key) => {
      dataSource.value = dataSource.value.filter((item) => item.key !== key)
      const res = await teacherDelete(key)
      console.log(res)
      getInfo()
    }
    // 查询
    const search = async () => {
      currentIndex.value = 1
      if (
        !formState.num &&
        !formState.name &&
        !formState.organization &&
        !formState.phone &&
        !formState.sex
      ) {
        roleInfo.searchInfo = []
        dataSource.value = []
        getInfo()
      } else {
        var data
        if (!formState.organization) {
          data = {
            tnumber: formState.num,
            teacherName: formState.name,
            department: '',
            tclass: '',
            phone: formState.phone,
            sex: formState.sex
          }
        } else {
          data = {
            tnumber: formState.num,
            teacherName: formState.name,
            department: formState.organization[0],
            tclass: formState.organization[1],
            phone: formState.phone,
            sex: formState.sex
          }
        }
        const result = await teacherSearch(data)
        if (result) {
          dataSource.value = []
          roleInfo.searchInfo = []
          for (let i = 0; i < result.length; i++) {
            roleInfo.searchInfo.push(result[i])
          }
          totalSize.value = roleInfo.searchInfo.length
          if (roleInfo.searchInfo.length > 5) {
            for (let i = 0; i < 5; i++) {
              dataSource.value.push(roleInfo.searchInfo[i])
            }
          } else {
            for (let i = 0; i < roleInfo.searchInfo.length; i++) {
              dataSource.value.push(roleInfo.searchInfo[i])
            }
          }
        }
      }
    }

    const onChange = async (pageNumber) => {
      currentIndex.value = pageNumber
      params.page = pageNumber
      if (roleInfo.searchInfo.length > 0) {
        totalSize.value = roleInfo.searchInfo.length
        dataSource.value = []
        if (roleInfo.searchInfo.length > currentIndex.value * 5) {
          for (let i = (currentIndex.value - 1) * 5; i < currentIndex.value * 5; i++) {
            dataSource.value.push(roleInfo.searchInfo[i])
          }
        } else {
          for (let i = (currentIndex.value - 1) * 5; i < roleInfo.searchInfo.length; i++) {
            dataSource.value.push(roleInfo.searchInfo[i])
          }
        }
      } else {
        const info = await teacherInfo(params)
        console.log(info.total)
        totalSize.value = info.total
        dataSource.value = []
        if (info.records.length > 0) {
          for (let i = 0; i < info.records.length; i++) {
            const fInfo = {
              key: info.records[i].id,
              teacherName: info.records[i].teacherName,
              department: info.records[i].department + '/' + info.records[i].tclass,
              sex: info.records[i].sex,
              phone: info.records[i].phone,
              tnumber: info.records[i].tnumber
            }
            const data = dataSource.value
            if (!data.find((item) => item.key === info.records[i].id)) {
              dataSource.value.push(fInfo)
            }
          }
        }
      }
    }

    const visible = ref(false)
    const showModal = () => {
      visible.value = true
    }
    const handleOk = () => {
      if (
        formStateModal.num &&
        formStateModal.name &&
        formStateModal.organization &&
        formStateModal.phone &&
        formStateModal.sex
      ) {
        const data = {
          tnumber: formStateModal.num,
          teacherName: formStateModal.name,
          department: formStateModal.organization[0],
          tclass: formStateModal.organization[1],
          phone: formStateModal.phone,
          sex: formStateModal.sex,
          id: 0
        }

        teacherAdd(data).then((res) => {
          formStateModal.num = ''
          formStateModal.name = ''
          formStateModal.organization = ''
          formStateModal.phone = ''
          formStateModal.sex = ''
        })
      } else {
      }
      visible.value = false
    }

    const afterClose = () => {
      formStateModal.num = ''
      formStateModal.name = ''
      formStateModal.organization = ''
      formStateModal.phone = ''
      formStateModal.sex = ''
    }
    onMounted(() => {
      getInfo()
    })
    const showSuccess = ref(false)
    const showError = ref(false)
    return {
      formRef,
      formState,
      sex,
      dataSource,
      columns,
      editingKey: '',
      editableData,
      formStateModal,
      currentIndex,
      pageSizeIndex,
      totalSize,
      options,
      showSuccess,
      showError,
      visible,
      edit,
      save,
      cancel,
      onDelete,
      search,
      resetFormData,
      onChange,
      showModal,
      handleOk,
      afterClose
    }
  }
})
</script>

<style scoped lang="less">
#components-form-demo-advanced-search .ant-form {
  max-width: none;
}
#components-form-demo-advanced-search .search-result-list {
  margin-top: 16px;
  border: 1px dashed #e9e9e9;
  border-radius: 2px;
  background-color: #fafafa;
  min-height: 200px;
  text-align: center;
  padding-top: 80px;
}
[data-theme='dark'] .ant-advanced-search-form {
  background: rgba(255, 255, 255, 0.04);
  border: 1px solid #434343;
  padding: 24px;
  border-radius: 2px;
}
[data-theme='dark'] #components-form-demo-advanced-search .search-result-list {
  border: 1px dashed #434343;
  background: rgba(255, 255, 255, 0.04);
}
.search-result-list {
  margin-top: 30px;
  box-shadow: 0px 0px 5px 5px #eee;
}
.aButton {
  margin-left: 35px;
}

.chaxun {
  border: 1px solid #eee;
  height: 200px;
  margin-top: -10px;
  padding-top: 15px;
  box-shadow: 0px 0px 5px 5px #eee;
  border-radius: 5px;
}

.ssBox {
  margin-top: 15px;
}
</style>
